/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useRef, useEffect } from "react";
import { connect, useSelector } from "dva";
import { Form, Table, Input, Button, Icon, Row, Col, message } from "antd";
import { useFormTable, useDebounceFn } from "@umijs/hooks";
import CheckQrCodeModal from "./CheckQrCodeModal";
import BindPost from "../components/BindPost";
import UnbindButton from "../components/UnbindButton";

const FormItem = Form.Item;

/**
 * @param path 下载路径
 * @param data 下载的参数
 */
const downLoad = (path, data = {}) => {
  const form = document.createElement("form");
  document.body.appendChild(form);
  Object.keys(data).forEach(item => {
    const input = document.createElement("input");
    input.type = "hidden";
    input.name = item;
    input.value = data[item];
    form.appendChild(input);
  });
  form.method = "GET";
  form.action = path;
  form.submit();
  document.body.removeChild(form);
};

const DataTable = props => {
  const { bindYz, isCityLeague } = useSelector(({ platform }) => platform);
  const { dispatch, form, activeKey, qrCodeDownLoadPath } = props;
  const { getFieldDecorator } = form;
  const [visible, setVisible] = useState(false);
  const [title, setTitle] = useState("");
  const [channel, setChannel] = useState("");
  const [record, setRecord] = useState({});
  const [qrCodeType, setQrCodeType] = useState("");
  const [exportLoading, setExportLoading] = useState(false);
  const [showBind, setShowBind] = useState(true);
  const timer = useRef(null);
  const tableCount = useRef(null);

  const getTableData = useCallback(
    ({ current, pageSize }, formData) => {
      return dispatch({
        type: "wxQrCode/wxGetQrList",
        payload: {
          type: activeKey == "operator" ? "courier" : "dak",
          page: current,
          size: pageSize,
          ...formData,
        },
      })
        .then(res => {
          const { data = {} } = res;
          const { total, list } = data;

          bindYz && setShowBind(false);
          
          if (current == 1) {
            // 缓存总数
            tableCount.current = total;
          }
          return {
            total: tableCount.current,
            list,
          };
        })
        .catch(code => {
          if (code == 9999) {
            setShowBind(true);
          }
        });
    },
    [activeKey, dispatch, bindYz]
  );

  const { tableProps, search, loading } = useFormTable(getTableData, {
    defaultPageSize: 20,
    form,
  });

  const { submit } = search;

  const handleClick = useCallback(
    ({ channel, type, record }) => {
      setTitle(
        `${type == "subscription" ? "公众号" : "小程序"}类型：${
          channel == "operator" ? "业务员揽件二维码" : "快宝驿站专属二维码"
        }`
      );
      setChannel(channel);
      showModal(true);
      setRecord(record);
      setQrCodeType(type == "subscription" ? "weixin" : "weixin_mini");
    },
    [showModal]
  );

  const showModal = useCallback(visible => {
    setVisible(visible);
  }, []);

  const columns =
    activeKey == "operator"
      ? [
          {
            title: "业务员",
            align: "center",
            dataIndex: "name",
          },
          {
            title: "业务员账号",
            align: "center",
            dataIndex: "account",
          },
          {
            title: "站点",
            align: "center",
            dataIndex: "address",
          },
          {
            title: "公众号二维码",
            align: "center",
            width: "10%",
            render: (text, record) => (
              <Button
                onClick={() => handleClick({ channel: "operator", type: "subscription", record })}
                type="primary"
              >
                查看
              </Button>
            ),
          },
          {
            title: "小程序二维码",
            align: "center",
            width: "10%",
            render: (text, record) => (
              <Button
                onClick={() => handleClick({ channel: "operator", type: "wxApp", record })}
                type="primary"
              >
                查看
              </Button>
            ),
          },
        ]
      : [
          {
            title: "驿站",
            align: "center",
            dataIndex: "name",
          },
          {
            title: "驿站账号",
            align: "center",
            dataIndex: "account",
          },
          {
            title: "站点",
            align: "center",
            dataIndex: "address",
          },
          {
            title: "公众号二维码",
            align: "center",
            width: "10%",
            render: (text, record) => (
              <Button
                onClick={() => handleClick({ channel: "site", type: "subscription", record })}
                type="primary"
              >
                查看
              </Button>
            ),
          },
          {
            title: "小程序二维码",
            align: "center",
            width: "10%",
            render: (text, record) => (
              <Button
                onClick={() => handleClick({ channel: "site", type: "wxApp", record })}
                type="primary"
              >
                查看
              </Button>
            ),
          },
        ];

  const handleSearch = e => {
    e.preventDefault();
    submit();
  };

  const getDownLoadURL = useCallback(
    () =>
      dispatch({
        type: "wxQrCode/wxQrDownLoad",
        payload: {
          type: activeKey == "operator" ? "courier" : "dak",
        },
      }),
    [activeKey]
  );

  const handleExport = useCallback(
    () => {
      const type = activeKey == "operator" ? "courier" : "dak";

      setExportLoading(true);
      dispatch({
        type: "wxQrCode/wxQrCreateExport",
        payload: {
          type,
        },
      })
        .then(() => {
          let time = 0;
          clearInterval(timer.current);

          timer.current = setInterval(() => {
            time++;
            if (time >= 10) {
              message.error("获取下载链接超时！");
              setExportLoading(false);
              clearInterval(timer.current);
            }
            getDownLoadURL();
          }, 1000 * 10);

          getDownLoadURL();
        })
        .catch(() => {
          setExportLoading(false);
        });
    },
    [activeKey, qrCodeDownLoadPath]
  );

  useEffect(
    () => {
      if (qrCodeDownLoadPath) {
        downLoad(qrCodeDownLoadPath);
        dispatch({
          type: "wxQrCode/save",
          payload: {
            qrCodeDownLoadPath: "",
          },
        });
      } else {
        setExportLoading(false);
        clearInterval(timer.current);
      }
      return () => {
        clearInterval(timer.current);
      };
    },
    [qrCodeDownLoadPath]
  );

  const { run: exprot } = useDebounceFn(() => {
    handleExport();
  }, 300);

  if (activeKey === "station" && !isCityLeague && !bindYz && showBind) {
    return <BindPost pagination={tableProps.pagination} refresh={tableProps.onChange} />;
  }

  return (
    <>
      <Form layout="inline" onSubmit={handleSearch} style={{ marginBottom: 15 }}>
        <Row type="flex" justify="space-between">
          <Col>
            <FormItem>
              {getFieldDecorator("search")(
                <Input
                  prefix={<Icon type="search" />}
                  style={{ width: 300 }}
                  placeholder={
                    activeKey == "operator"
                      ? "请输入业务员姓名或账号搜索"
                      : "请输入快宝驿站名称或账号搜索"
                  }
                />
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" htmlType="submit" loading={loading}>
                搜索
              </Button>
            </FormItem>
          </Col>
          <Col>
            {activeKey === "station" &&
              !isCityLeague && (
                <FormItem>
                  <UnbindButton onRefresh={submit} />
                </FormItem>
              )}
            {/* <FormItem>
              <Button type="primary" onClick={exprot} loading={exportLoading}>
                {exportLoading ? "正在导出，请勿刷新页面" : "导出"}
              </Button>
            </FormItem> */}
          </Col>
        </Row>
      </Form>
      <Table rowKey="id" columns={columns} {...tableProps} />
      <CheckQrCodeModal
        visible={visible}
        title={title}
        showModal={showModal}
        channel={channel}
        record={record}
        type={activeKey == "operator" ? "courier" : "dak"}
        qrCodeType={qrCodeType}
        currentPage={tableProps.pagination}
        refreshCurrent={tableProps.onChange}
      />
    </>
  );
};

export default connect(({ wxQrCode }) => ({
  qrCodeDownLoadPath: wxQrCode.qrCodeDownLoadPath,
}))(Form.create()(DataTable));
